package com.atguigu.juc_day02;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * java
 * 2022/9/8 13 57
 * 1、故障现象
 *  java.util.ConcurrentModificationException
 *  并发修改异常：ConcurrentModificationException
 */
public class NotSafeDemo {
    public static void main (String[] args) {
     /*   HashMap<String, String > hashMap = new HashMap<> ();
        for (int i = 0; i < 30; i++) {
            new Thread (()->{
                hashMap.put (Thread.currentThread ().getName (), UUID.randomUUID ().toString ().substring (0,8));
                System.out.println (hashMap);
            },String.valueOf (i)).start ();
        }*/
        NotSafeDemo.setNotSafe ();
    }
    private static void setNotSafe(){
        //使用Collections的synchronizedList方法生成自带锁的List。
        List<String> strings = Collections.synchronizedList (new ArrayList<> ());
        for (int i = 0; i < 30; i++) {
            new Thread (()->{
                strings.add (UUID.randomUUID ().toString ().substring (0,8));
                System.out.println (strings);
            }).start ();
        }
    }

    /**
     * 写时复制解决线程不安全问题
     * 1.效率最优。
     * 2.最为方便。
     */
    private static void setNotSafe2(){
        CopyOnWriteArrayList<String> strings = new CopyOnWriteArrayList<> ();
        for (int i = 0; i < 30; i++) {
            new Thread (()->{
                strings.add (UUID.randomUUID ().toString ().substring (0,8));
                System.out.println (strings);
            }).start ();
        }
    }
}
